package com.kucai.yifaqapp.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kucai.yifaqapp.R;
import com.kucai.yifaqapp.dagger.component.activity.DaggerLauncherActivityComponent;
import com.kucai.yifaqapp.dagger.module.activity.LauncherActivityModule;
import com.kucai.yifaqapp.global.App;
import com.kucai.yifaqapp.global.HttpAdress;
import com.kucai.yifaqapp.global.Info;
import com.kucai.yifaqapp.model.CustomObserver;
import com.kucai.yifaqapp.model.network.HttpJsonApi;
import com.kucai.yifaqapp.model.network.HttpJsonUtils;
import com.kucai.yifaqapp.model.network.entity.res.AppVersionInfo;
import com.kucai.yifaqapp.presenter.activity.LauncherActivityPresenter;
import com.kucai.yifaqapp.ui.fragment.LauncherViewPagerHomeFragment;
import com.kucai.yifaqapp.ui.fragment.LauncherViewPagerMoneyFragment;
import com.kucai.yifaqapp.ui.fragment.LauncherViewPagerResultFragment1;
import com.kucai.yifaqapp.ui.fragment.LauncherViewPagerUserFragment1;
import com.kucai.yifaqapp.ui.view.LauncherActivityView;
import com.kucai.yifaqapp.util.DownloadUtil;
import com.kucai.yifaqapp.util.EventBus.ReloginEvent;
import com.kucai.yifaqapp.util.EventBus.goTomoneyEvent;
import com.kucai.yifaqapp.util.SYSOUtils;
import com.kucai.yifaqapp.util.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class LauncherActivity extends BaseActivity<LauncherActivityPresenter> implements LauncherActivityView, View.OnClickListener {
    FrameLayout content;
    RelativeLayout home;
    RelativeLayout result;
    RelativeLayout valeet;
    RelativeLayout user;
    ImageView home_pic;
    ImageView result_pic;
    ImageView valeet_pic;
    ImageView user_pic;
    LinearLayout skinbg;
    ProgressDialog progressDialog;
    private Fragment home_fragment = new LauncherViewPagerHomeFragment();
    private Fragment result_fragment = new LauncherViewPagerResultFragment1();
    private Fragment valeet_fragment = new LauncherViewPagerMoneyFragment();
    private Fragment user_fragment = new LauncherViewPagerUserFragment1();

    /**
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViewAndEvent();
        initFragment();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        //开始下载安装apk
//        getAppVersion();
    }

    private void initViewAndEvent() {
        content = findViewById(R.id.content);
        home = findViewById(R.id.home);
        result = findViewById(R.id.result);
        valeet = findViewById(R.id.valeet);
        user = findViewById(R.id.user);
        home_pic = findViewById(R.id.home_pic);
        result_pic = findViewById(R.id.result_pic);
        valeet_pic = findViewById(R.id.valeet_pic);
        user_pic = findViewById(R.id.user_pic);
        skinbg = findViewById(R.id.skinbg);
        home.setOnClickListener(this);
        result.setOnClickListener(this);
        valeet.setOnClickListener(this);
        user.setOnClickListener(this);
    }

    public static String getLocalVersion(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    private void getAppVersion() {
        HttpJsonUtils.getHttpApiInstance()
                .get_APP_version(getString(R.string.getAppVersion))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new CustomObserver<AppVersionInfo>(this) {
                    @Override
                    protected void onCustomNext(AppVersionInfo resBanner) {
                        Log.e("xdh", resBanner.getVersion() + "**********" + ("" + getLocalVersion(LauncherActivity.this)));
                        if (resBanner.getVersion().equals("" + getLocalVersion(LauncherActivity.this))) {
                        } else {
                            Log.e("xdh", resBanner.getUrl());
                            downFile(resBanner.getUrl());
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    private void initFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (!home_fragment.isAdded()) {
            ft.add(R.id.content, home_fragment, "1");
        }
        if (!result_fragment.isAdded()) {
            ft.add(R.id.content, result_fragment, "2");
        }
        if (!valeet_fragment.isAdded()) {
            ft.add(R.id.content, valeet_fragment, "3");
        }
        if (!user_fragment.isAdded()) {
            ft.add(R.id.content, user_fragment, "4");
        }
        ft.commitAllowingStateLoss();
        changeFragmemt("1");
    }

    public void changeFragmemt(String tag) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (tag.equals("1")) {
            ft.show(home_fragment);
            ft.hide(result_fragment);
            ft.hide(valeet_fragment);
            ft.hide(user_fragment);
            home_pic.setBackgroundResource(R.mipmap.tab_ic_home_on);
            result_pic.setBackgroundResource(R.mipmap.tab_ic_result_off);
            valeet_pic.setBackgroundResource(R.mipmap.tab_ic_money_off);
            user_pic.setBackgroundResource(R.mipmap.tab_ic_user_off);
        } else if (tag.equals("2")) {
            ft.show(result_fragment);
            ft.hide(home_fragment);
            ft.hide(valeet_fragment);
            ft.hide(user_fragment);
            home_pic.setBackgroundResource(R.mipmap.tab_ic_home_off);
            result_pic.setBackgroundResource(R.mipmap.tab_ic_result_on);
            valeet_pic.setBackgroundResource(R.mipmap.tab_ic_money_off);
            user_pic.setBackgroundResource(R.mipmap.tab_ic_user_off);
        } else if (tag.equals("3")) {
            ft.show(valeet_fragment);
            ft.hide(home_fragment);
            ft.hide(result_fragment);
            ft.hide(user_fragment);
            home_pic.setBackgroundResource(R.mipmap.tab_ic_home_off);
            result_pic.setBackgroundResource(R.mipmap.tab_ic_result_off);
            valeet_pic.setBackgroundResource(R.mipmap.tab_ic_money_on);
            user_pic.setBackgroundResource(R.mipmap.tab_ic_user_off);
        } else {
            ft.show(user_fragment);
            ft.hide(home_fragment);
            ft.hide(result_fragment);
            ft.hide(valeet_fragment);
            home_pic.setBackgroundResource(R.mipmap.tab_ic_home_off);
            result_pic.setBackgroundResource(R.mipmap.tab_ic_result_off);
            valeet_pic.setBackgroundResource(R.mipmap.tab_ic_money_off);
            user_pic.setBackgroundResource(R.mipmap.tab_ic_user_on);
        }
        ft.commitAllowingStateLoss();
    }

    @Override
    protected void initDagger() {
        DaggerLauncherActivityComponent.builder()
                .launcherActivityModule(new LauncherActivityModule(this))
                .build().inject(this);

    }

    @Override
    protected int setContentView() {
        return R.layout.activity_launcher;
    }

    @Override
    protected void ChangeSkin() {
        switch (SkinId) {
            case 17771:
                skinbg.setBackgroundResource(R.mipmap.skin_bg1);
                break;
            case 17772:
                skinbg.setBackgroundResource(R.mipmap.skin_bg2);
                break;
            case 17773:
                skinbg.setBackgroundResource(R.mipmap.skin_bg3);
                break;
            default:
                skinbg.setBackgroundResource(R.mipmap.skin_bg1);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home:
                changeFragmemt("1");
                break;
            case R.id.result:
                if (Info.user == null) {
                    startActivity(new Intent(LauncherActivity.this, LoginActivity.class));
                    return;
                } else {
                    changeFragmemt("2");
                }

                break;
            case R.id.valeet:
                if (Info.user == null) {
                    startActivity(new Intent(LauncherActivity.this, LoginActivity.class));
                    return;
                } else {
                    if (Info.user.userName == null) {
                        startActivity(new Intent(LauncherActivity.this, LoginActivity.class));
                    } else {
                        changeFragmemt("3");
                    }
                }
                break;
            case R.id.user:
                if (Info.user == null) {
                    startActivity(new Intent(LauncherActivity.this, LoginActivity.class));
                    return;
                } else {
                    changeFragmemt("4");
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //个人中新 资金管理跳转
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(goTomoneyEvent messageEvent) {
        switch (messageEvent.getMessage()) {
            case "1":
                changeFragmemt("1");
                break;
            case "2":
                break;
            case "3":
                changeFragmemt("3");
                break;
            case "4":
                break;
        }
    }

    //code=600重新登录
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(ReloginEvent messageEvent) {
        Toast.makeText(this, "token过期，请清空用户信息重新登录", Toast.LENGTH_SHORT).show();
        Info.user = null;
        SpUtils.clearUser(this);
        startLogin();
    }


    /**
     * 下载apk
     */
    private void downFile(String url) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("正在更新至最新的程序..." + "\r\n" + "请稍后...");
        progressDialog.setMax(100);
        progressDialog.show();
        DownloadUtil.get().download(url, Environment.getExternalStorageDirectory().getAbsolutePath(), File.separator + System.currentTimeMillis() + "_newdown.apk",
                new DownloadUtil.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        //下载完成进行相关逻辑操作,现在是子线程
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                install(file);
                            }
                        });
                    }

                    @Override
                    public void onDownloading(int progress) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressDialog.setProgress(progress);
                            }
                        });
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LauncherActivity.this, "下载失败，请检查网络设置", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
    }


    private void install(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    this
                    , "com.kucai.yifaqapp.fileprovider"
                    , apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }
}
